#!/bin/sh
# Copyright (c) 2013, bkil.hu
# This program is free software and can be distributed under the terms of
# the GNU General Public License v2,
# see COPYING for detailed licensing terms.
# created on 2013-01-20
#
# Automatically updates dynamical IPv4 and IPv6 addresses.
# Supports afraid.org,
# miredo (Teredo over remlab) and gogoc (TSP over freenet6)

main() {
 CFG="/etc/v6-afraid.conf"
 if [ ! -f "$CFG" ]; then
  echo "error: please fill out the generated $CFG" >&2
  cat << EOF >> "$CFG"
FORCEUPDATE=600 # minutes
HASH4="" # can be left empty
HASH6="" # paste the hash (part after "?") of the IPv6 Direct URL here
EOF
  exit 1
 fi

 . "$CFG"

 if [ -z "$HASH6" -o -z "$FORCEUPDATE" ]; then
  echo "error: HASH6 and FORCEUPDATE must be set in $CFG" >&2
  exit 1
 fi

 I=0
 NOIPMAX=3
 GOGOCMAX=8
 CNTNOIP=0
 while true; do
  IP6=`for ADAPTER in teredo tun sit0 sit1; do
        ifconfig $ADAPTER 2>/dev/null
       done |
       grep "\<inet6 addr.*\<Scope:Global\>" |
       head -n 1 |
       sed "s~^.*inet6 addr: \([^/ ]*\)/.*$~\1~"`

  if [ $I -eq 0 ]; then
   OLDIP6=""
   I=$FORCEUPDATE
   echo "info: forcing update" >&2
  else
   I=`expr $I - 1`
  fi

  if [ -z "$IP6" ]; then
   CNTNOIP=`expr $CNTNOIP + 1`
   if pidof gogoc > /dev/null; then
    if [ $CNTNOIP -ge $GOGOCMAX ]; then
     echo "error: IPv6 tunnel lost, restarting gogoc (IPv4 update also skipped)" >&2
     service gogoc restart
     CNTNOIP=0
    else
     echo "debug: still waiting for gogoc to get an IP" >&2
    fi
   else
    if [ $CNTNOIP -ge $NOIPMAX ]; then
     echo "error: IPv6 tunnel lost, starting gogoc (IPv4 update also skipped)" >&2
     service gogoc restart
     CNTNOIP=0
    else
     echo "debug: throttling gogoc before restart" >&2
    fi
   fi
  else
  CNTNOIP=0
  if ! [ "$IP6" = "$OLDIP6" ]; then
   echo "info: updating to $IP6" >&2
   case "_$HASH4" in
    _http*) URL4="$HASH4" ;;
    _)      URL4="" ;;
    *)      URL4="https://freedns.afraid.org/dynamic/update.php?${HASH4}"
   esac

   if [ -n "$URL4" ]; then
    wget -4 -nv -O - --timeout 30 --tries 10 "$URL4"
    S4=$?
   else
    S4=0
   fi

   case "$HASH6" in
    http*) URL6="$HASH6" ;;
    *)     URL6="https://freedns.afraid.org/dynamic/update.php?${HASH6}&address=$IP6"
   esac
   wget -6 -nv -O - --timeout 30 --tries 10 "$URL6"
   S6=$?
   if [ $S6 -ne 0 ]; then
    wget -nv -O - --timeout 30 --tries 10 "$URL6"
    S6=$?
   fi
   if [ $S4 -eq 0 ] && [ $S6 -eq 0 ]; then
    OLDIP6="$IP6"
   else
    echo "error: update failed" >&2
   fi
  fi
  fi

  sleep 60
 done
}

main "$@"
